package com.maxd.controller.selfAliPay;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.maxd.adapter.IgnoreSecurity;
import com.maxd.constants.AliPayConstants;
import com.maxd.error.Result;
import com.maxd.error.ResultUtil;
import com.maxd.model.*;
import com.maxd.modules.selfshop.merchants.entity.SelfMargin;
import com.maxd.modules.selfshop.merchants.entity.SelfMerchantApply;
import com.maxd.modules.selfshop.merchants.entity.SelfStore;
import com.maxd.modules.selfshop.merchants.respository.SelfMerchantApplyJpaRepository;
import com.maxd.modules.selfshop.merchants.respository.SelfStoreJpaRepository;
import com.maxd.modules.selfshop.merchants.service.SelfMarginService;
import com.maxd.modules.selfshop.merchants.service.SelfStoreService;
import com.maxd.respository.common.CommonRepository;
import com.maxd.respository.selfGoods.GoodsJpaRepository;
import com.maxd.respository.selfGroup.SelfGroupJpaRepository;
import com.maxd.respository.selfGroupPink.SelfGroupPinkJpaRepository;
import com.maxd.respository.selfOrder.OrdersJpaRepository;
import com.maxd.respository.selfOrderRemind.SelfOrdersRemindJpaRepository;
import com.maxd.respository.selfSeckill.SelfSeckillJpaRepository;
import com.maxd.service.money.IMoneyDetailsService;
import com.maxd.service.selfGoods.GoodsService;
import com.maxd.service.selfGoodsVirtual.SelfGoodsVirtualService;
import com.maxd.service.selfOrder.OrdersService;
import com.maxd.service.userinfo.IUserService;
import com.maxd.utils.Config;
import com.maxd.utils.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.*;

@Api(value = "自营商城支付宝支付", tags = {"自营商城支付宝支付"})
@Slf4j
@RestController
@RequestMapping("/aliPay")
public class SelfAliPayController {

    @Autowired
    private CommonRepository commonRepository;
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private OrdersJpaRepository ordersJpaRepository;
    @Autowired
    private SelfGoodsVirtualService selfGoodsVirtualService;
    @Autowired
    private IUserService userService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private SelfStoreService selfStoreService;
    @Autowired
    private SelfMerchantApplyJpaRepository selfMerchantApplyJpaRepository;
    @Autowired
    private SelfMarginService selfMarginService;
    @Autowired
    private SelfOrdersRemindJpaRepository selfOrdersRemindJpaRepository;
    @Autowired
    private SelfGroupPinkJpaRepository selfGroupPinkJpaRepository;
    @Autowired
    private IMoneyDetailsService iMoneyDetailsService;
    @Autowired
    private GoodsJpaRepository goodsJpaRepository;
    @Autowired
    private SelfGroupJpaRepository selfGroupJpaRepository;
    @Autowired
    private SelfSeckillJpaRepository selfSeckillJpaRepository;
    @Autowired
    private SelfStoreJpaRepository selfStoreJpaRepository;


    /**
     * 创建线程池处理业务逻辑
     */
    private ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().build();
    private ExecutorService singleThreadPool = new ThreadPoolExecutor(30, 100,
            0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());

    /**
     * 支付宝网页支付
     *
     * @param response
     * @throws IOException
     */
    @RequestMapping("/payment")
    public void aliPay(HttpServletResponse response, String payNum, Long userId, BigDecimal payMoney) throws IOException {
        String one2 = commonRepository.findOne(19).getValue();
        String url = one2 + "/tao/aliPay/notifyH5";
        String returl = commonRepository.findOne(298).getValue();
        CommonInfo one1 = commonRepository.findOne(12);
        String body = one1.getValue();
        List<Orders> list = new ArrayList<>();
        for (String pay : payNum.split(",")) {
            List<Orders> byPayNum = ordersService.findByPayNum(pay);
            list.addAll(byPayNum);
        }
        if (list.size() > 0) {
            body = list.get(0).getTitle();
        }
        //支付金额校验
        BigDecimal paySum = new BigDecimal("0.00");
        for (Orders o : list) {
            paySum = paySum.add(o.getPayMoney());
        }
        log.info("支付金额，传入金额：" + payMoney + "计算金额：" + paySum);
        payMoney = paySum;
        AlipayClient alipayClient = new DefaultAlipayClient(AliPayConstants.REQUEST_URL,
                commonRepository.findOne(63).getValue(), commonRepository.findOne(65).getValue(), AliPayConstants.FORMAT,
                AliPayConstants.CHARSET, commonRepository.findOne(64).getValue(), AliPayConstants.SIGNTYPE);


        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(url);
        request.setReturnUrl(returl);
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", payNum);
        bizContent.put("total_amount", String.valueOf(payMoney));
        bizContent.put("subject", body);
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        request.setBizContent(bizContent.toString());
        try {
            AlipayTradePagePayResponse response1 = alipayClient.pageExecute(request);
            String body1 = response1.getBody();
            response.setContentType("text/html;charset=" + AliPayConstants.CHARSET);
            response.getWriter().write(body1);
            response.getWriter().flush();
            response.getWriter().close();
        } catch (AlipayApiException e) {
            e.printStackTrace();
            log.info("支付宝支付异常，异常信息为:" + e.getErrMsg(), e);
        }

    }


    /**
     * 支付宝网页支付
     */
    @IgnoreSecurity
    @ApiOperation("网站扫码支付")
    @GetMapping("/payWeb")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public Result aliPay(@RequestParam Long orderId) {
        //订单信息
        Orders o = ordersJpaRepository.findById(orderId).orElse(null);
        String one2 = commonRepository.findOne(19).getValue();
        String returnUrl = commonRepository.findOne(298).getValue(); //商户端域名
        String url = one2 + "/tao/aliPay/notifyWeb"; //回调地址
        //url = "http://2o9t550523.qicp.vip:37499/aliPay/notifyWeb"; //本地域名测试
        AlipayClient alipayClient = new DefaultAlipayClient(AliPayConstants.REQUEST_URL,
                commonRepository.findOne(63).getValue(), commonRepository.findOne(65).getValue(), AliPayConstants.FORMAT,
                AliPayConstants.CHARSET, commonRepository.findOne(64).getValue(), AliPayConstants.SIGNTYPE);
        AlipayTradePagePayModel aliPayParamModel = new AlipayTradePagePayModel();
        aliPayParamModel.setOutTradeNo(o.getPayNum());
        aliPayParamModel.setSubject(o.getTitle());
        aliPayParamModel.setBody(o.getTitle());
        aliPayParamModel.setTotalAmount(o.getPayMoney().toString());
        aliPayParamModel.setProductCode("FAST_INSTANT_TRADE_PAY");
        aliPayParamModel.setTimeoutExpress("30m");
        AlipayTradePagePayRequest aliPayRequest = new AlipayTradePagePayRequest();
        aliPayRequest.setReturnUrl(returnUrl);
        aliPayRequest.setNotifyUrl(url);
        aliPayRequest.setBizModel(aliPayParamModel);
        AlipayTradePagePayResponse response = null;
        try {
            // 调用SDK生成表单
            response = alipayClient.pageExecute(aliPayRequest);
            log.info("支付宝支付拉取正常，信息为:" + response.getBody());
            if (response.isSuccess()) {
                return ResultUtil.success(response);
            }
            return ResultUtil.error(-1, "支付失败，请稍后再试");
        } catch (AlipayApiException e) {
            log.info("支付宝支付异常，异常信息为:" + e.getErrMsg());
            e.printStackTrace();
            return ResultUtil.error(-1, "支付失败，请稍后再试");
        }
    }

    @IgnoreSecurity
    @ApiOperation("app支付保障金")
    @GetMapping("/payAppMargin")
    @Transactional(rollbackFor = Exception.class)
    public Result payAppMargin(Long orderId) {
        //订单信息
        Orders o = ordersJpaRepository.findById(orderId).orElse(null);
        String one2 = commonRepository.findOne(19).getValue();
        String returnUrl = commonRepository.findOne(247).getValue(); //商户端域名
        String url = one2 + "/tao/aliPay/notifyWeb"; //回调地址
        //实例化客户端
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", commonRepository.findOne(63).getValue(), commonRepository.findOne(65).getValue(), "json", AliPayConstants.CHARSET, commonRepository.findOne(64).getValue(), "RSA2");
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setBody(o.getTitle());
        model.setSubject(o.getTitle());
        model.setOutTradeNo(o.getPayNum());
        model.setTimeoutExpress("30m");
        model.setTotalAmount(o.getPayMoney().toString()); //金额
        model.setProductCode("QUICK_MSECURITY_PAY");
        request.setBizModel(model);
        request.setNotifyUrl(url);
        request.setReturnUrl(returnUrl);
        try {
            AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
            if (response.isSuccess()) {
                return ResultUtil.success(response.getBody());
            } else {
                log.info("调用失败");
                ResultUtil.error(-100, "获取订单失败！");
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return ResultUtil.error(-100, "获取订单失败！");

    }

    @IgnoreSecurity
    @ApiOperation("h5支付保障金")
    @GetMapping(value = "/payH5Margin")
    @Transactional(rollbackFor = Exception.class)
    public Result payH5Margin(Long orderId) {
        //订单信息
        Orders o = ordersJpaRepository.findById(orderId).orElse(null);
        String one2 = commonRepository.findOne(19).getValue();
        String returnUrl = commonRepository.findOne(247).getValue(); //商户端域名
        String url = one2 + "/tao/aliPay/notifyWeb"; //回调地址
        try {
            AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", commonRepository.findOne(63).getValue(), commonRepository.findOne(65).getValue(), "json", AliPayConstants.CHARSET, commonRepository.findOne(64).getValue(), "RSA2");
            AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
            JSONObject order = new JSONObject();
            order.put("out_trade_no", o.getPayNum()); //订单号
            order.put("subject", o.getTitle()); //商品标题
            order.put("product_code", "QUICK_WAP_WAY");
            order.put("body", o.getTitle());//商品名称
            order.put("total_amount", o.getPayMoney().toString()); //金额
            alipayRequest.setBizContent(order.toString());
            alipayRequest.setNotifyUrl(url); //在公共参数中设置回跳和通知地址
            alipayRequest.setReturnUrl(returnUrl); //线上通知页面地址
            String form = alipayClient.pageExecute(alipayRequest).getBody();
            return ResultUtil.success(form);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return ResultUtil.error(-100, "获取订单失败！");
    }


    /**
     * 网站支付回调
     *
     * @param request
     * @return
     */
    @IgnoreSecurity
    @RequestMapping("notifyWeb")
    @Transactional(rollbackFor = Exception.class)
    public void returnUrl(HttpServletRequest request, HttpServletResponse response) {
        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        try {
            boolean flag = AlipaySignature.rsaCheckV1(params, commonRepository.findOne(64).getValue(), AliPayConstants.CHARSET, "RSA2");
            if (flag) {
                String tradeStatus = params.get("trade_status");
                if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)) {
                    String outTradeNo = params.get("out_trade_no");
                    //支付成功，处理业务
                    Orders orders = ordersService.findByPayNum(outTradeNo).get(0);
                    if (orders.getStatus() == 1) {
                        //订单业务
                        orders.setPayWay(8); //支付方式为8支付宝网页
                        orders.setStatus(10); //10已评价
                        orders.setPayTime(DateUtil.createTime()); //设置支付时间
                        orders.setFinishTime(DateUtil.createTime()); //设置完成时间
                        ordersService.updateBody(orders);
                        //保证金明细
                        SelfMargin m = new SelfMargin();
                        m.setCreateTime(DateUtil.createTime()); //创建时间
                        m.setMerchantId(orders.getMerchantId()); //商户id
                        m.setStoreName(orders.getConsignee()); //店铺名称
                        m.setOrderId(orders.getId()); //订单id
                        m.setOrderNum(orders.getOrderNum()); //订单号
                        m.setMarginType(orders.getType().intValue()); //保证金类型
                        m.setMarginMoney(orders.getPayMoney()); //保证金金额
                        selfMarginService.saveBody(m);
                    }
                }

            }
        } catch (AlipayApiException e) {
            log.info("支付宝回调验签异常：" + e.getMessage());
            e.printStackTrace();
        }
    }


    /**
     * app支付回调
     */
    @IgnoreSecurity
    @RequestMapping("/notifyApp")
    @Transactional(rollbackFor = Exception.class)
    public void notifyApp(HttpServletRequest request, HttpServletResponse response) {
        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        try {
            log.info("回调成功！！！");
            boolean flag = AlipaySignature.rsaCheckV1(params, commonRepository.findOne(64).getValue(), AliPayConstants.CHARSET, "RSA2");
            log.info(flag + "回调验证信息");
            if (flag) {
                String tradeStatus = params.get("trade_status");
                if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)) {
                    String outTradeNo = params.get("out_trade_no");
                    this.payBack(outTradeNo, 4); //支付方式（1app微信 2微信公众号 3微信小程序 4app支付宝 5H5支付宝 6零钱
                }

            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
            log.info("回调验证失败！！！");
        }
    }

    /**
     * H5支付回调
     */
    @IgnoreSecurity
    @RequestMapping("/notifyH5")
    @Transactional(rollbackFor = Exception.class)
    public void notifyH5(HttpServletRequest request, HttpServletResponse response) {
        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        try {
            log.info("回调成功！！！");
            boolean flag = AlipaySignature.rsaCheckV1(params, commonRepository.findOne(64).getValue(), AliPayConstants.CHARSET, "RSA2");
            log.info(flag + "回调验证信息");
            if (flag) {
                String tradeStatus = params.get("trade_status");
                if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)) {
                    String outTradeNo = params.get("out_trade_no");
                    this.payBack(outTradeNo, 5); //支付方式（1app微信 2微信公众号 3微信小程序 4app支付宝 5H5支付宝 6零钱
                }
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
            log.info("回调验证失败！！！");
        }
    }

    /**
     * 支付回调业务
     */
    private void payBack(String payNum, Integer payWay) {
        //支付成功，处理业务
        List<Orders> list = ordersService.findByPayNum(payNum);
        for (Orders orders : list) {
            if (orders.getPayWay() != null) {
                log.info("订单回调重复：" + orders.toString());
                return;
            }
            SelfOrderRemind r = new SelfOrderRemind();
            r.setOrdersId(orders.getId());
            r.setCreateTime(DateUtil.createTime());
            r.setStatus(1);
            r.setType(1);
            if (orders.getMerchantId() != null) {
                r.setMerchantId(orders.getMerchantId());
            }
            selfOrdersRemindJpaRepository.save(r);

            orders.setPayWay(payWay); //支付方式（1app微信 2微信公众号 3微信小程序 4app支付宝 5H5支付宝 6零钱）
            orders.setStatus(2); //已付款
            orders.setPayTime(DateUtil.createTime()); //设置支付时间
            //4.订单业务
            if (orders.getOrderType() == 1) { //普通订单
                //4.1虚拟商品处理
                if (orders.getIsExpress() == 2) { //是否需要发货(1需要发货 2无需发货)
                    //虚拟商品发货，发货成功为确认收货，否则不做变化
                    SelfGoodsVirtual v = selfGoodsVirtualService.sendGoods(orders.getId());
                    if (v != null) {
                        orders.setVirtualId(v.getId()); //虚拟商品id
                        orders.setExpressTime(DateUtil.createTime()); //发货时间
                        orders.setFinishTime(DateUtil.createTime()); //收货时间
                        orders.setStatus(4); //确认收货
                        //虚拟发货成功商户业务
                        if (orders.getStoreId() != null) {
                            //商品销量增加
                            goodsService.salesAdd(orders.getGoodsId(), orders.getNumber());
                            //商户销量增加
                            selfStoreService.salesAdd(orders.getStoreId(), orders.getNumber());
                            //商户余额增加
                            SelfMerchantApply m = selfMerchantApplyJpaRepository.findById(orders.getMerchantId()).orElse(null);
                            if(m.getMoney()==null){
                                m.setMoney(BigDecimal.ZERO);
                            }
                            SelfStore selfStore = selfStoreJpaRepository.findById(orders.getStoreId()).orElse(null);
                            BigDecimal pingMoney = selfStore.getRate().multiply(orders.getStoreMoney());
                            BigDecimal storeMoney=orders.getStoreMoney().subtract(pingMoney);
                            storeMoney=storeMoney.setScale(2,BigDecimal.ROUND_HALF_DOWN);
                            selfMerchantApplyJpaRepository.updateMoneyAdd(m.getMoney().add(storeMoney), orders.getMerchantId());
                            iMoneyDetailsService.saveMerchant(m.getId(),1,1,"订单到账："+orders.getOrderNum(),"到账金额："+storeMoney,storeMoney.doubleValue());

                        }
                    }
                } else if (orders.getIsExpress() == 3) { //核销订单
                    orders.setStatus(3); //待收货、待使用
                }
                //4.2拼团业务处理
            } else if (orders.getOrderType() == 2) {
                orders.setStatus(9);
                ordersService.pink(orders);
            }
            ordersService.updateBody(orders);
            //订单分销
            ordersService.fenXiao(orders.getId());
            //公众号消息通知
            userService.orderPay(orders.getUserId(), orders.getOrderNum(), orders.getPayMoney().toString(), orders.getCreateAt());
        }
    }


    @IgnoreSecurity
    @ApiOperation("app支付")
    @GetMapping("/payApp")
    @Transactional(rollbackFor = Exception.class)
    public Result payApp(String payNum, Long userId, BigDecimal payMoney) {
        log.info("开始下单了！！");
        String one2 = commonRepository.findOne(19).getValue();
        String url = one2 + "/tao/aliPay/notifyApp";
        //url="http://2o9t550523.qicp.vip/aliPay/notifyApp"; //本地测试地址
        String returl = commonRepository.findOne(297).getValue();
        log.info("回调地址:" + url);
        //实例化客户端
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", commonRepository.findOne(63).getValue(), commonRepository.findOne(65).getValue(), "json", AliPayConstants.CHARSET, commonRepository.findOne(64).getValue(), "RSA2");
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        String body = Config.BASE_NAME;
        List<Orders> list = ordersService.findByPayNum(payNum);
        if (list.size() > 0) {
            body = list.get(0).getTitle();
        }
        //支付金额校验
        BigDecimal paySum = new BigDecimal("0.00");
        for (Orders o : list) {
            if(o.getGroupId()!=null){
                SelfGroup selfGroup = selfGroupJpaRepository.findById(o.getGroupId()).orElse(null);
                if(selfGroup==null || selfGroup.getStatus()!=1){
                    return ResultUtil.error(-200, "商品已被下架或移除，请选择其他商品！");
                }
            }else if(o.getSecKillId()!=null){
                SelfSecKill selfSecKill = selfSeckillJpaRepository.findById(o.getSecKillId()).orElse(null);
                if(selfSecKill==null || selfSecKill.getStatus()!=1){
                    return ResultUtil.error(-200, "商品已被下架或移除，请选择其他商品！");
                }
            }else if(o.getGoodsId()!=null){
                Goods g = goodsJpaRepository.findById(o.getGoodsId()).orElse(null);
                if(g==null || g.getStatus()!=1){
                    return ResultUtil.error(-200, "商品已被下架或移除，请选择其他商品！");
                }
            }
            paySum = paySum.add(o.getPayMoney());
            if (o.getStatus() != 1) {
                return ResultUtil.error(-200, "订单已经支付过了！");
            }
            if (o.getGroupPinkId() != null) {
                SelfGroupPink selfGroupPink = selfGroupPinkJpaRepository.findById(o.getGroupPinkId()).orElse(null);
                if (selfGroupPink.getStatus() == 2) {
                    return ResultUtil.error(-200, "拼团已完成，无法参与！");
                }
            }
        }
        log.info("支付金额，传入金额：" + payMoney + "计算金额：" + paySum);
        payMoney = paySum;
        model.setBody(body);
        model.setSubject(body);
        model.setOutTradeNo(payNum);
        model.setTimeoutExpress("30m");
        model.setTotalAmount(payMoney + ""); //金额
        model.setProductCode("QUICK_MSECURITY_PAY");
        request.setBizModel(model);
        request.setNotifyUrl(url);
        request.setReturnUrl(returl);
        try {
            AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
            if (response.isSuccess()) {
                return ResultUtil.success(response.getBody());
            } else {
                log.info("调用失败");
                ResultUtil.error(-100, "获取订单失败！");
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return ResultUtil.error(-100, "获取订单失败！");

    }

    @IgnoreSecurity
    @ApiOperation("h5支付")
    @GetMapping(value = "/payH5")
    @Transactional(rollbackFor = Exception.class)
    public Result payH5(String payNum, Long userId, BigDecimal payMoney) {
        String one2 = commonRepository.findOne(19).getValue();
        String url = one2 + "/tao/aliPay/notifyH5";
        String returl = commonRepository.findOne(297).getValue();
        log.info("回调地址:" + url);
        try {
            CommonInfo one1 = commonRepository.findOne(12);
            AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", commonRepository.findOne(63).getValue(), commonRepository.findOne(65).getValue(), "json", AliPayConstants.CHARSET, commonRepository.findOne(64).getValue(), "RSA2");
            AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
            JSONObject order = new JSONObject();
            order.put("out_trade_no", payNum); //订单号
            String body = Config.BASE_NAME;
            List<Orders> list = ordersService.findByPayNum(payNum);
            if (list.size() > 0) {
                body = list.get(0).getTitle();
            }
            //支付金额校验
            BigDecimal paySum = new BigDecimal("0.00");
            for (Orders o : list) {
                if(o.getGroupId()!=null){
                    SelfGroup selfGroup = selfGroupJpaRepository.findById(o.getGroupId()).orElse(null);
                    if(selfGroup==null || selfGroup.getStatus()!=1){
                        return ResultUtil.error(-200, "商品已被下架或移除，请选择其他商品！");
                    }
                }else if(o.getSecKillId()!=null){
                    SelfSecKill selfSecKill = selfSeckillJpaRepository.findById(o.getSecKillId()).orElse(null);
                    if(selfSecKill==null || selfSecKill.getStatus()!=1){
                        return ResultUtil.error(-200, "商品已被下架或移除，请选择其他商品！");
                    }
                }else if(o.getGoodsId()!=null){
                    Goods g = goodsJpaRepository.findById(o.getGoodsId()).orElse(null);
                    if(g==null || g.getStatus()!=1){
                        return ResultUtil.error(-200, "商品已被下架或移除，请选择其他商品！");
                    }
                }
                paySum = paySum.add(o.getPayMoney());
                if (o.getStatus() != 1) {
                    return ResultUtil.error(-200, "订单已经支付过了！");
                }
                if (o.getGroupPinkId() != null) {
                    SelfGroupPink selfGroupPink = selfGroupPinkJpaRepository.findById(o.getGroupPinkId()).orElse(null);
                    if (selfGroupPink.getStatus() == 2) {
                        return ResultUtil.error(-200, "拼团已完成，无法参与！");
                    }
                }
            }
            log.info("支付金额，传入金额：" + payMoney + "计算金额：" + paySum);
            payMoney = paySum;
            order.put("subject", Config.BASE_NAME); //商品标题
            order.put("product_code", "QUICK_WAP_WAY");
            order.put("body", body);//商品名称
            order.put("total_amount", payMoney + ""); //金额
            alipayRequest.setBizContent(order.toString());
            alipayRequest.setNotifyUrl(url); //在公共参数中设置回跳和通知地址
            alipayRequest.setReturnUrl(returl); //线上通知页面地址
            String form = alipayClient.pageExecute(alipayRequest).getBody();
            return ResultUtil.success(form);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return ResultUtil.error(-100, "获取订单失败！");
    }
}
